#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
银行账单解析模块
"""

import pandas as pd
import chardet
from typing import List, Dict
from datetime import datetime
import re
import warnings
import os
warnings.filterwarnings('ignore')

from wechat_parser import Transaction


def parse_bank_bill(file_path: str) -> List[Transaction]:
    """解析银行账单文件"""
    try:
        # 检查文件扩展名
        if file_path.endswith('.csv'):
            return parse_bank_bill_csv(file_path)
        elif file_path.endswith(('.xlsx', '.xls')):
            return parse_bank_bill_excel(file_path)
        else:
            raise ValueError(f"不支持的文件格式: {file_path}")
    except Exception as e:
        raise ValueError(f"解析银行账单时出错: {str(e)}")


def parse_bank_bill_csv(file_path: str) -> List[Transaction]:
    """解析银行账单CSV格式"""
    # 自动检测文件编码
    with open(file_path, 'rb') as f:
        raw_data = f.read()
        encoding = chardet.detect(raw_data)['encoding']
    
    # 读取CSV文件
    df = pd.read_csv(file_path, encoding=encoding)
    
    # 删除完全为空的行
    df = df.dropna(how='all')
    
    # 查找关键列名
    time_col = None
    type_col = None
    amount_col = None
    payee_col = None
    note_col = None
    
    # 查找交易时间列
    for col in df.columns:
        if '交易时间' in str(col):
            time_col = col
            break
    
    # 查找收支类型列
    for col in df.columns:
        if '收/支' in str(col) or '收入/支出' in str(col):
            type_col = col
            break
    
    # 查找金额列
    for col in df.columns:
        if '金额' in str(col) or '交易金额' in str(col):
            amount_col = col
            break
    
    # 查找交易对方列
    for col in df.columns:
        if '交易对方' in str(col) or '对方户名' in str(col):
            payee_col = col
            break
    
    # 查找商品说明列
    for col in df.columns:
        if '商品' in str(col) or '用途' in str(col) or '摘要' in str(col):
            note_col = col
            break
    
    # 如果找不到关键列，抛出异常
    if not all([time_col, type_col, amount_col]):
        raise ValueError("无法找到必要的列：交易时间、收/支、金额")
    
    transactions = []
    
    # 解析每一行数据
    for _, row in df.iterrows():
        try:
            # 解析交易时间
            timestamp = row.get(time_col, '')
            if pd.isna(timestamp) or timestamp == '':
                continue
            
            # 解析交易类型（收入/支出）
            trans_type = str(row.get(type_col, ''))
            if trans_type not in ['收入', '支出']:
                # 尝试从金额正负判断类型
                amount_str = str(row.get(amount_col, '0'))
                # 处理金额，去除货币符号和逗号
                amount_value = float(re.sub(r'[¥,\s]', '', amount_str))
                trans_type = '收入' if amount_value > 0 else '支出'
            
            # 处理金额，去除货币符号和逗号
            amount_str = str(row.get(amount_col, '0'))
            amount_value = float(re.sub(r'[¥,\s]', '', amount_str))
            
            # 根据交易类型调整金额符号
            if trans_type == '收入':
                amount = abs(amount_value)
            else:
                amount = -abs(amount_value)
            
            # 创建Transaction对象
            transaction = Transaction(
                timestamp=str(timestamp),
                amount=amount,
                type=trans_type,
                category='',  # 需要后续分类
                payee=str(row.get(payee_col, '')) if payee_col else '',
                source='bank',
                note=str(row.get(note_col, '')) if note_col else '',
                subcategory=''  # 二级分类
            )
            transactions.append(transaction)
        except Exception as e:
            # 跳过解析失败的行
            continue
    
    return transactions


def parse_bank_bill_excel(file_path: str) -> List[Transaction]:
    """解析银行账单Excel格式"""
    # 读取Excel文件
    df = pd.read_excel(file_path, header=None)
    
    # 查找包含列名的行
    header_row_index = None
    for i in range(min(20, len(df))):  # 在前20行中查找
        row = df.iloc[i]
        if '交易时间' in str(row.tolist()):
            header_row_index = i
            break
    
    if header_row_index is None:
        raise ValueError("无法找到银行账单的列名行")
    
    # 重新读取数据，设置正确的列名
    df_data = pd.read_excel(file_path, header=header_row_index)
    
    # 删除完全为空的行
    df_data = df_data.dropna(how='all')
    
    # 清理列名
    df_data.columns = [str(col).strip() for col in df_data.columns]
    
    # 查找关键列名
    time_col = None
    type_col = None
    amount_col = None
    payee_col = None
    note_col = None
    
    # 查找交易时间列
    for col in df_data.columns:
        if '交易时间' in str(col):
            time_col = col
            break
    
    # 查找收支类型列
    for col in df_data.columns:
        if '收/支' in str(col) or '收入/支出' in str(col):
            type_col = col
            break
    
    # 查找金额列
    for col in df_data.columns:
        if '金额' in str(col) or '交易金额' in str(col):
            amount_col = col
            break
    
    # 查找交易对方列
    for col in df_data.columns:
        if '交易对方' in str(col) or '对方户名' in str(col):
            payee_col = col
            break
    
    # 查找商品说明列
    for col in df_data.columns:
        if '商品' in str(col) or '用途' in str(col) or '摘要' in str(col):
            note_col = col
            break
    
    # 如果找不到关键列，抛出异常
    if not all([time_col, type_col, amount_col]):
        raise ValueError("无法找到必要的列：交易时间、收/支、金额")
    
    transactions = []
    
    # 解析每一行数据
    for _, row in df_data.iterrows():
        try:
            # 解析交易时间
            timestamp = row.get(time_col, '')
            if pd.isna(timestamp) or timestamp == '':
                continue
            
            # 解析交易类型（收入/支出）
            trans_type = str(row.get(type_col, ''))
            if trans_type not in ['收入', '支出']:
                # 尝试从金额正负判断类型
                amount_str = str(row.get(amount_col, '0'))
                # 处理金额，去除货币符号和逗号
                amount_value = float(re.sub(r'[¥,\s]', '', amount_str))
                trans_type = '收入' if amount_value > 0 else '支出'
            
            # 处理金额，去除货币符号和逗号
            amount_str = str(row.get(amount_col, '0'))
            amount_value = float(re.sub(r'[¥,\s]', '', amount_str))
            
            # 根据交易类型调整金额符号
            if trans_type == '收入':
                amount = abs(amount_value)
            else:
                amount = -abs(amount_value)
            
            # 创建Transaction对象
            transaction = Transaction(
                timestamp=str(timestamp),
                amount=amount,
                type=trans_type,
                category='',  # 需要后续分类
                payee=str(row.get(payee_col, '')) if payee_col else '',
                source='bank',
                note=str(row.get(note_col, '')) if note_col else '',
                subcategory=''  # 二级分类
            )
            transactions.append(transaction)
        except Exception as e:
            # 跳过解析失败的行
            continue
    
    return transactions